/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.map;

import com.flexengine.logger.Logger;
import com.flexengine.xml.Persister;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class GameMapManager {
    
    public static GameMap load(String file) {
        try {
            Persister persister = new Persister();
            GameMap map = null;
            if( file.endsWith(".zip") ) {
                ZipFile zipFile = new ZipFile(file);
                String entryName = file.replace(".zip", ".xml");
                ZipEntry entry = zipFile.getEntry(file.replace(".zip", ".xml"));
                if( entry==null ) {
                    throw new Exception("ZIP-FILE does'nt caontains a MAP with name["+entryName+"]!");
                }
                map = persister.read(GameMap.class, zipFile.getInputStream(entry));
            }
            else {
                map = persister.read(GameMap.class, file);
            }
            // -- load the texture used in loading state...
            if( map.getLoadTexture()!=null ) {
                map.getLoadTexture().loadImage();
            }
            return map;
        } catch(Exception e) {
            Logger.logError("GameMapManager::load() - "+e);
        }
        return null;
    }
    
    public static void saveCompressed(GameMap map) {
        try {
            Persister serializer = new Persister();
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                serializer.writer(map, out);
                try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(map.getName()+".zip"))) {
                    zipOut.putNextEntry(new ZipEntry(map.getName()+".xml"));
                    zipOut.write(out.toByteArray());
                    zipOut.closeEntry();
                }
            }
        } catch(Exception e) {
            Logger.logError("GameMapManager::saveCompressed() - "+e);
        }
    }
    public static void save(GameMap map) {
        try {
            Persister persister = new Persister();
            persister.writer(map, "./"+map.getName()+".xml");
        } catch(Exception e) {
            Logger.logError("GameMapManager::save() - "+e);
        }
    }
    
}
